package org.mogu.service;

import java.io.IOException;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.mogu.control.model.IMUser;
import org.mogu.db.ActiveUserHelper;
import org.mogu.db.DBhelper;
import org.mogu.staticvalue.Convert;
import org.mogu.tools.UrlSync;
import org.mogu.tools.UserUtil;

import org.mogu.R;
import org.mogu.TMain;
import org.mogu.Welcome;


import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;
import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.os.Binder;

import android.os.Handler;

public class InfoService extends Service {

	private Handler mMainHandler;

	InfoSync infoSync = new InfoSync();
//	ImgLibSync imgLibSync = new ImgLibSync();
	ImgSync imgSync = new ImgSync();
	GetSyncUrl getSyncUrl;
	DefaultHttpClient client;
	HttpResponse httpResponse;
	ActiveUserHelper auh;
	SQLiteDatabase readdb;
	SQLiteDatabase writedb;

	String uname;
	String pwd;
	String updateTime;

	Context context;

	ContentValues value;
	Intent i;
	Vibrator vibrator;
	
	 int numt=1;
	 
	int num = 0;
	/**
	 * 　　* 创建Handler对象，作为进程传递postDelayed之用
	 * 
	 * 　　
	 */

	private static final String TAG = "TService";

	private NotificationManager notificationManager;
	private MediaPlayer mp;
	
	long[] pattern = {100, 50, 400, 30}; // OFF/ON/OFF/ON...  

	public void onCreate() {
		
		UserUtil.getUser(this);
		Convert.flag+=1;
		Log.d(TAG, "============> TService.onCreate");
		context = this;
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);   
		 
		
		auh = DBhelper.getDBHelper(this);
		getSyncUrl=new GetSyncUrl(auh);
		getSyncUrl.init();

		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		ContentValues activeuser = new ContentValues();
		activeuser.put("title", "-1");
		synchronized (InfoSync.class) {
			auh.getWritableDatabase().update("content", activeuser, "title='-2'", null);
		}

		super.onCreate();
		mMainHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				// // 接收子线程的消息
				UrlSync urlSync=(UrlSync)msg.obj;
				if(msg.arg1==1){
					if(urlSync.isNotice()){
//						MobclickAgent.reportError(context,urlSync.getNoticeTitle()+"_title_"+urlSync.getNoticeContent()+"_content_"+urlSync.getNoticeCode()+"_code_");
						putNotic(urlSync.getNoticeTitle(),urlSync.getNoticeContent(),urlSync.getNoticeCode());
						vibrator.vibrate(pattern, -1);
						ring();
					}else{
						if(urlSync.isToast()){
							if(urlSync.getToastContentSu()!=null){
								
							Toast.makeText(context, urlSync.getToastContentSu(), 4000).show();
							}
						}else{
							if(urlSync.getToastContentFa()!=null){
								
								Toast.makeText(context, urlSync.getToastContentFa(), 4000).show();
								}
						}
					}
				}else{
					Toast.makeText(context, "网络不给力。", 4000).show();
				}
				
			}

		};
	}

	private void ring() {
		try {
			if (mp == null) {
				mp=MediaPlayer.create(context, R.raw.info);
//				Uri alert = RingtoneManager
//						.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//				MediaPlayer player = new MediaPlayer();
//				player.reset();
//
//				player.setDataSource(context, alert);
//
//				final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//				if (audioManager
//						.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {
//					player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
//
//				}
//				player.setLooping(false);
//				player.prepare();
			}
			mp.stop();
			mp.prepare();
			mp.start();
		} catch (Exception e) {
			Log.e("sound", "声音失败。");
//			Log.e("sounderr", e.getMessage());
		}

	}

//		return player;

	private Handler handler = new Handler();
	private Handler imghandler = new Handler();

	public void onStart(Intent intent, int startId) {

		Log.i(TAG, "============> TService.onStart");
		super.onStart(intent, startId);
//		Toast.makeText(context, "~~~~~~"+Convert.flag, 4000).show();
		new Thread() {
			public void run() {
				Log.e("Service", "sync1");
				auh = DBhelper.getDBHelper(context);
				
				infoSync.sync(auh);
				getSyncUrl.getNeedSyncUrl();
				// auh.close();
				Log.e("Service", "sync4");
				long l=60*2;
				Long long1;
				for (String key : Convert.userAppTimeSpanMap.keySet()) {
					long1=Convert.userAppTimeSpanMap.get(key);
					Log.e("Service", "time-"+long1);
					if(long1.longValue()<l){
						l=long1.longValue();
					}
				}
				
				handler.postDelayed(this, l*1000);
				Log.e("Service", "sync5-"+l);
			}
		}.start();
		new Thread() {
			public void run() {

				// auh=DBhelper.getDBHelper(context);
				// sync(auh);//要定时执行的任务
				// auh.close();
				Log.e("Service", "ImgSync");
				imgsync();
				if(Convert.hasImage){
					imghandler.postDelayed(this, 1000 * 30 * 1);
				}else{
					imghandler.postDelayed(this, 1000 * 30 * 6);
				}
				
			}
		}.start();
		// imgsync();
		th.start();
	}

	public IBinder onBind(Intent intent) {

		Log.i(TAG, "============> TService.onBind");

		return null;
	}

	public class LocalBinder extends Binder {

		public InfoService getService() {

			return InfoService.this;
		}

	}

	public boolean onUnbind(Intent intent) {

		Log.i(TAG, "============> TService.onUnbind");

		return false;
	}

	public void onRebind(Intent intent) {

		Log.i(TAG, "============> TService.onRebind");
	}

	public void onDestroy() {

		Log.i(TAG, "============> TService.onDestroy");

		notificationManager.cancel(R.string.service_start);

		super.onDestroy();
	}

	public void showNotification(String title,String content) {
		i = new Intent(InfoService.this, TMain.class);
		 NotificationManager nm = (NotificationManager)
		 getSystemService(NOTIFICATION_SERVICE);
		 Notification n = new Notification(R.drawable.moguico, "蘑菇咨询",
		 System.currentTimeMillis());
		 n.flags = Notification.FLAG_AUTO_CANCEL;
		 // Intent i = new Intent(arg0.getContext(), NotificationShow.class);
		 //
		 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
		 // PendingIntent
		 PendingIntent contentIntent = PendingIntent.getActivity(this,
		 R.string.app_name, i, PendingIntent.FLAG_UPDATE_CURRENT);
		
		 n.setLatestEventInfo(this, title, content, contentIntent);
		 nm.notify(numt++, n);
	}

	public void onDestory() {

	}

	public Thread th = new Thread() {
		public void run() {
//			Looper.prepare();
			UrlSync urlSync=null;
			
			while (true) {
				boolean b=false;
				while (true) {
					synchronized (Convert.class) {
						if(Convert.syncList.size()!=0){
							urlSync=Convert.syncList.remove(0);
						}else{
							b=true;
						}
					}
					if(b){
						break;
					}
					request(urlSync);
					try {

						if (Convert.urlfail) {
							sleep(Convert.failTimeSpan * 1000);
//							Log.e("synctime", String.valueOf(Convert.failTimeSpan));
						} 

					} catch (InterruptedException e) {
					}
				}
				try {

					if (Convert.urlfail) {
						sleep(Convert.failTimeSpan * 1000);
//						Log.e("synctime", String.valueOf(Convert.failTimeSpan));
					} else {
						sleep(1000);
//						Log.e("synctime", String.valueOf(1));
					}

				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
//					e.printStackTrace();
				}
				
			}
		}
	};
	HttpGet getMet;
	HttpPost postMet;

	public void request(UrlSync urlSync) {
		try {
		if (urlSync==null){
			return;
		}
		getMet = null;
		postMet = null;
		if (urlSync.isGet()) {
			getMet = new HttpGet(urlSync.getAllUri());
		} else {
			postMet = new HttpPost(urlSync.getAllUri());
			postMet.setEntity(new UrlEncodedFormEntity(urlSync.getPrarm(),HTTP.UTF_8));
		}
		Log.e("request", urlSync.getAllUri());
		client = new DefaultHttpClient();
		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
		client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		
			if (urlSync.isGet()) {
				httpResponse = client.execute(getMet);

			} else {
				httpResponse = client.execute(postMet);
			}
			int statusCode=httpResponse.getStatusLine().getStatusCode();

//			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 取出回应字串
				String strResult;

				strResult = EntityUtils.toString(httpResponse.getEntity());
					Log.e("request", "1");
					urlSync.setResult(strResult);
					if(urlSync.getResultType()==null){
						if(!"1".equals(strResult)&&statusCode==200){
						infoSync.savecontnet(strResult, auh,  urlSync);
						}
					}
					if("1".equals(urlSync.getResultType())||"2".equals(urlSync.getResultType())){
						if("1".equals(strResult)&&statusCode==200){
							urlSync.setToast(false);
						}
					}
					if("16".equals(urlSync.getResultType())||"10".equals(urlSync.getResultType())||"21".equals(urlSync.getResultType())){
						if("1".equals(strResult)||statusCode!=200){
							urlSync.setToast(false);
						}else{
							setWebUrl(strResult.split(";"));
						}
					}
					if("9".equals(urlSync.getResultType())){
						if("1".equals(strResult)||statusCode!=200){
							urlSync.setToast(false);
						}else{
							if(urlSync.getAllUri().contains("/delWeibo")){
								String[] bindArgs={Convert.uname,urlSync.getCode()};
								auh.getWritableDatabase().execSQL("delete from content where username=? and code=? ", bindArgs);
							}else{
								setWebUrl(strResult.split(";"));
							}
							
						}
					}
					if("31".equals(urlSync.getResultType())){//聊天，发送信息。
						IMUser imuser=urlSync.getImUser();
						String[] arr={imuser.getCode(),imuser.getUname()};
						if("1".equals(strResult)||statusCode!=200){
							urlSync.setNotice(false);
							urlSync.setToast(false);
							ContentValues activeuser = new ContentValues();
							activeuser.put("title", "-1");
							synchronized (InfoSync.class) {
								auh.getWritableDatabase().update("content", activeuser, "code=? and username=?", arr);
							}
						}else{
							
							ContentValues activeuser = new ContentValues();
							activeuser.put("code",imuser.getCode() );
							activeuser.put("maincode", imuser.getMaincode());
							activeuser.put("username", imuser.getUname());
							activeuser.put("content", imuser.getContent());
							activeuser.put("title", imuser.getTitle());
							activeuser.put("status", "1");
							activeuser.put("level", imuser.getLevel());
							activeuser.put("father", imuser.getFather());
							activeuser.put("replyType", imuser.getReplyType());
							activeuser.put("lastUpdateTime", urlSync.getResult());
							
							synchronized (InfoSync.class) {
								auh.getWritableDatabase().update("content", activeuser, "code=? and username=?", arr);
//								auh.getWritableDatabase().insert("content", null, activeuser);
							}
						}
						if(urlSync.getHandler()!=null){
							Message msg=urlSync.getHandler().obtainMessage();
							msg.obj=urlSync;
							msg.arg1=1;
							urlSync.getHandler().sendMessage(msg);
//							ring();
							return;
						}
					}
					if("32".equals(urlSync.getResultType())){//查找用户
						if("1".equals(strResult)||statusCode!=200){
							urlSync.setNotice(false);
							urlSync.setToast(false);
						}else{
							
							if(urlSync.getHandler()!=null){
								Message msg=urlSync.getHandler().obtainMessage();
								msg.obj=urlSync;
								msg.arg1=1;
								urlSync.getHandler().sendMessage(msg);
								return;
							}
							
						}
					}
					if("33".equals(urlSync.getResultType())){//删除好友
						if("1".equals(strResult)||statusCode!=200){
							urlSync.setNotice(false);
							urlSync.setToast(false);
						}else{
							IMUser imuser=urlSync.getImUser();
							ContentValues activeuser = new ContentValues();
//							activeuser.put("code",imuser.getCode() );
							activeuser.put("title", "2");
							imuser.setTitle("2");
							String[] arr={Convert.uname,imuser.getCode()};
							synchronized (InfoSync.class) {
								auh.getWritableDatabase().update("content", activeuser, "username=? and code=?", arr);
							}
							if(urlSync.getHandler()!=null){
								Message msg=urlSync.getHandler().obtainMessage();
								msg.obj=urlSync;
								msg.arg1=1;
								urlSync.getHandler().sendMessage(msg);
								return;
							}
							
						}
					}
					if("34".equals(urlSync.getResultType())){//添加好友
						if("1".equals(strResult)||statusCode!=200){
							urlSync.setNotice(false);
							urlSync.setToast(false);
						}else{
							IMUser imuser=urlSync.getImUser();
							JSONObject user=new JSONObject();
							
							ContentValues activeuser = new ContentValues();
							activeuser.put("title", "1");
							imuser.setTitle("1");
							String[] where={imuser.getCode(),Convert.uname};
							synchronized (InfoSync.class) {
								int num=DBhelper.getDBHelper(this).getWritableDatabase().update("content", activeuser, "code=? and username=?", where);
								
								if(num==0){
									UserUtil.getJsonbyImUser(user, imuser);
									activeuser.put("code",imuser.getCode() );
									activeuser.put("username", Convert.uname);
									activeuser.put("maincode", imuser.getMaincode());
									activeuser.put("content", user.toString());
									activeuser.put("status", "1");
									activeuser.put("level", "101");
									activeuser.put("father", imuser.getMaincode()+"-s1");
									activeuser.put("replyType", "30");
									activeuser.put("lastUpdateTime", Convert.format1.format(new Date()));
									
									DBhelper.getDBHelper(this).getWritableDatabase().insert("content", null, activeuser);
								}
								
							}
							if(urlSync.getHandler()!=null){
								Message msg=urlSync.getHandler().obtainMessage();
								msg.obj=urlSync;
								msg.arg1=1;
								urlSync.getHandler().sendMessage(msg);
								return;
							}
							
						}
					}
					if("35".equals(urlSync.getResultType())){//修改用户信息
						if("1".equals(strResult)||statusCode!=200){
							urlSync.setToast(false);
						}else{
							IMUser imuser=urlSync.getImUser();
							JSONObject user=new JSONObject();
							String[] where={imuser.getCode(),Convert.uname};
							ContentValues activeuser = new ContentValues();
							UserUtil.getJsonbyImUser(user, imuser);
							synchronized (InfoSync.class) {
								activeuser.put("content", user.toString());
								DBhelper.getDBHelper(this).getWritableDatabase().update("content", activeuser, "code=? and username=?", where);
							}
							setWebUrl(strResult.split(";"));
							if(urlSync.getHandler()!=null){
								Message msg=urlSync.getHandler().obtainMessage();
								msg.obj=urlSync;
								msg.arg1=1;
								urlSync.getHandler().sendMessage(msg);
								return;
							}
						}
					}
					if("36".equals(urlSync.getResultType())){//删除好友
						if("1".equals(strResult)||statusCode!=200){
							urlSync.setNotice(false);
							urlSync.setToast(false);
						}else{
//							IMUser imuser=urlSync.getImUser();
//							ContentValues activeuser = new ContentValues();
////							activeuser.put("code",imuser.getCode() );
//							activeuser.put("title", "2");
//							imuser.setTitle("2");
//							String[] arr={Convert.uname,imuser.getCode()};
//							synchronized (InfoSync.class) {
//								auh.getWritableDatabase().update("content", activeuser, "username=? and code=?", arr);
//							}
							if(urlSync.getHandler()!=null){
								Message msg=urlSync.getHandler().obtainMessage();
								msg.obj=urlSync;
								msg.arg1=2;
								urlSync.getHandler().sendMessage(msg);
								return;
							}
							
						}
					}
					
					
					Message msg=mMainHandler.obtainMessage();
					msg.obj=urlSync;
					msg.arg1=1;
					mMainHandler.sendMessage(msg);

//			}else{
//				Log.e("requestErr", EntityUtils.toString(httpResponse.getEntity()));
//				MobclickAgent.reportError(context,EntityUtils.toString(httpResponse.getEntity()));
//			}
			Convert.urlfail=false;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			synchronized (Convert.class) {
				Convert.syncList.add(urlSync);
			}
			Message msg=mMainHandler.obtainMessage();
			msg.obj=urlSync;
			msg.arg1=2;
			mMainHandler.sendMessage(msg);
			
			
			Convert.urlfail=true;
			Log.e("requestErr", "2");
			

		} finally {

		}

	}
	
	private void setWebUrl(String[] weburl){
		UrlSync urlSync;
		for (String weburi : weburl) {
			if("".equals(weburi)){
				continue;
			}
			urlSync=new UrlSync();
			urlSync.setNotice(false);
			urlSync.setUri(weburi);
			urlSync.setMaincode("main");
			urlSync.setSyncType(UrlSync.INFOALL);
			synchronized (Convert.class) {
				Convert.syncList.add(0,urlSync);
			}
		}
	}
	


	public void imgsync() {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			auh = DBhelper.getDBHelper(context);
			Log.e("ImgNum", String.valueOf(num));
			if (num % 10 == 4) {
				imgSync.sync(null, auh, 1);
			} else {
				if (num % 10 == 7) {
					imgSync.sync(null, auh, 2);
				} else {
					imgSync.sync(null, auh, 0);
				}
			}
			num++;
		}
	}

	
	public void putNotic( String title, String content, String code) {
		// int s=new Date().getSeconds();
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification n = new Notification(R.drawable.moguico, content,
				System.currentTimeMillis());
		n.flags = Notification.FLAG_AUTO_CANCEL;
		// Intent i = new Intent(arg0.getContext(), NotificationShow.class);
		// i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
		// PendingIntent
		PendingIntent contentIntent = PendingIntent.getActivity(this,
				R.string.app_name, getI(code),
				PendingIntent.FLAG_UPDATE_CURRENT);

		n.setLatestEventInfo(this, title, content, contentIntent);

		nm.notify(numt++, n);
	}

	public Intent getI(String code) {
		int count = 0;
		try {
			synchronized (InfoSync.class) {
				readdb = auh.getReadableDatabase();
				Cursor activelist = readdb.rawQuery(
						"select * from activeuser ", null);
				count = activelist.getCount();
				activelist.close();
			}
		} catch (Exception t) {
			Log.e("E", t.getMessage() == null ? "" : t.getMessage());

		}

		// readdb.close();
		// auh.close();
		if (count == 0) {
			i = new Intent(InfoService.this, TMain.class);
		} else {
			i = new Intent(InfoService.this, Welcome.class);
			Uri uri = Uri.parse("?code:" + code);
			i.setData(uri);

		}

		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

		return i;
	}

}
